asynx.impl.cookie = {
	
	initCookies: function () {
		var allCookies = document.cookie.split('; '), cookiePair = [];
		for (var i=0;i<allCookies.length;i++) {
			cookiePair = allCookies[i].split('=');
			asynx.globals.cookies.cookiesCached[cookiePair[0]] = cookiePair[1];
		}
	},
	
	/**
	 * create a cookie
	 * 
	 * @author ppk book
	 * @param {Object} name
	 * @param {Object} value
	 * @param {Object} days
	 */
	createCookie: function(name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
		asynx.globals.cookies.cookiesCached[name] = value;
		this.initCookies();
	},
	
	/**
	 * read a cookie
	 * 
	 * @author ppk book
	 * @param {Object} name
	 */
	readCookie: function(name) {
		return asynx.globals.cookies.cookiesCached[name];
	},
	
	/**
	 * erase a cookie
	 * 
	 * @author ppk book
	 * @param {Object} name
	 */
	eraseCookie: function(name) {
		this.createCookie(name,"",-1);
		asynx.globals.cookies.cookiesCached[name] = undefined;
	},
	
	/**
	 * split the cookie value in a lot of pieces and stores all
	 * useful when the cookie you need is bigger than 266 bytes
	 * @param {Object} name
	 * @param {Object} value
	 * @param {Object} days
	 */
	createSplitedCookie: function(name,value,days) {
		var valueEncoded = encodeURIComponent(value);
		var bufferSize = 200;
		var piece = 0;
		var numberOfPieces = Math.ceil(valueEncoded.length / bufferSize);
		
		for(var x = 0; x < valueEncoded.length; x++) {
			if (x%bufferSize == 0) {
				var pieceValue = valueEncoded.substring(piece*bufferSize, (piece+1) * bufferSize);
				var nameOfPiece = name + "_" + piece;
				this.createCookie(nameOfPiece,pieceValue,days);
				piece++;
			}
		}
	},
	
	/**
	 * read all pices and return the full string
	 * @param {Object} name
	 */
	readSplitedCookie: function(name) {
		var piece = 0;
		var cookieValue = "";
		
		while(true) {
			var pieceValue = this.readCookie(name + '_' + piece);
			if (pieceValue == null) break;
			
			if (pieceValue != 'undefined')
				cookieValue += pieceValue;
				
			piece++;
		}
		
		return decodeURIComponent(cookieValue);
	},
	
	/**
	 * erase all cookie pices
	 * @param {Object} name
	 */
	eraseSplitedCookie: function(name) {
		var piece = 0;
		var cookieValue;
		
		while(true) {
			var namePiece = name + '_' + piece;
			var pieceValue = this.readCookie(namePiece);
			if (typeof pieceValue != 'string') break;
			this.eraseCookie(namePiece);
			piece++;
		}
	}
};
asynx.extend(asynx, asynx.impl.cookie);
delete asynx.impl.cookie;
